package com.study.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * @author zhuzi
 * 2024/5/11 14:28
 */
public class Fastjson2RedisSerializer<T> implements RedisSerializer<T> {

    private final Class<T> clazz;

    public Fastjson2RedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        try {
            // 使用Fastjson2进行序列化，并返回字节数组
            return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes();
        } catch (Exception e) {
            throw new SerializationException("Could not serialize", e);
        }
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            // 使用Fastjson2进行反序列化
            String jsonString = new String(bytes);
            return JSON.parseObject(jsonString, clazz, JSONReader.Feature.SupportAutoType);
        } catch (Exception e) {
            throw new SerializationException("Could not deserialize", e);
        }
    }
}
